#include "board.h"
#include "hpm_gptmr_drv.h"

void timer_config_ms(GPTMR_Type * GPTMR,uint8_t ch_index,uint32_t priority,uint16_t ms)
{
    uint32_t gptmr_freq;
    gptmr_channel_config_t config;
    uint32_t GPTMR_BASE_INDEX = (uint32_t)(GPTMR - HPM_GPTMR0_BASE);
    uint8_t GPTMR_Number = GPTMR_BASE_INDEX/0x4000;
    clock_name_t clock_name;
    switch(GPTMR_Number)
    {
        case 0:clock_name = clock_gptmr0; break;
        case 1:clock_name = clock_gptmr1; break;
        case 2:clock_name = clock_gptmr2; break;
        case 3:clock_name = clock_gptmr3; break;
        case 4:clock_name = clock_gptmr4; break;
        case 5:clock_name = clock_gptmr5; break;
        case 6:clock_name = clock_gptmr6; break;
        case 7:clock_name = clock_gptmr7; break;
    }

    gptmr_channel_get_default_config(GPTMR, &config);

    gptmr_freq = clock_get_frequency(clock_name);
    config.reload = gptmr_freq / 1000 * ms;
    gptmr_channel_config(GPTMR, ch_index, &config, false);
    gptmr_start_counter(GPTMR, ch_index);

    gptmr_enable_irq(GPTMR, GPTMR_CH_RLD_IRQ_MASK(ch_index));


    intc_m_enable_irq_with_priority((IRQn_GPTMR0+GPTMR_Number), priority);
}

void timer_config_us(GPTMR_Type * GPTMR,uint8_t ch_index,uint32_t priority,uint16_t us)
{
    uint32_t gptmr_freq;
    gptmr_channel_config_t config;
    uint32_t GPTMR_BASE_INDEX = (uint32_t)(GPTMR - HPM_GPTMR0_BASE);
    uint8_t GPTMR_Number = GPTMR_BASE_INDEX/0x4000;
    clock_name_t clock_name;
    switch(GPTMR_Number)
    {
        case 0:clock_name = clock_gptmr0; break;
        case 1:clock_name = clock_gptmr1; break;
        case 2:clock_name = clock_gptmr2; break;
        case 3:clock_name = clock_gptmr3; break;
        case 4:clock_name = clock_gptmr4; break;
        case 5:clock_name = clock_gptmr5; break;
        case 6:clock_name = clock_gptmr6; break;
        case 7:clock_name = clock_gptmr7; break;
    }

    gptmr_channel_get_default_config(GPTMR, &config);

    gptmr_freq = clock_get_frequency(clock_name);
    config.reload = gptmr_freq / 1000 * us;
    gptmr_channel_config(GPTMR, ch_index, &config, false);
    gptmr_start_counter(GPTMR, ch_index);

    gptmr_enable_irq(GPTMR, GPTMR_CH_RLD_IRQ_MASK(ch_index));


    intc_m_enable_irq_with_priority((IRQn_GPTMR0+GPTMR_Number), priority);
}


hpm_stat_t gptmr_channel_Rconfig(GPTMR_Type *ptr,
                         uint8_t ch_index,
                         gptmr_channel_config_t *config,
                         bool enable)
{
    uint32_t tmp_value;
    tmp_value = config->reload;
    if (tmp_value > 0) {
        tmp_value--;
    }
    ptr->CHANNEL[ch_index].RLD = GPTMR_CHANNEL_RLD_RLD_SET(tmp_value);
    return status_success;
}

void timer_Rconfig_us(GPTMR_Type * GPTMR,uint8_t ch_index,uint32_t us)
{
    static  gptmr_channel_config_t config;
    config.reload = 100 * us;
    gptmr_channel_Rconfig(GPTMR, ch_index, &config, true);
}